<script setup>
import { ref, onMounted, computed } from 'vue';
import { getUsers } from '../../api/services';

const props = defineProps({
  selectedUserId: {
    type: String,
    default: ''
  },
  dateRange: {
    type: Object,
    default: () => ({
      startDate: '2023-10-01',
      endDate: new Date().toISOString().split('T')[0]
    })
  }
});

const emit = defineEmits(['select-user']);

const users = ref([]);
const loading = ref(true);
const searchQuery = ref('');

// 根据搜索筛选用户
const filteredUsers = computed(() => {
  if (!searchQuery.value) return users.value;
  
  const query = searchQuery.value.toLowerCase();
  return users.value.filter(user => 
    user.nickname?.toLowerCase().includes(query) || 
    user.location?.toLowerCase().includes(query)
  );
});

// 模拟数据，当API请求失败时使用
const mockUsers = [
  {
    user_id: 'user001',
    nickname: '跑步爱好者',
    location: '北京',
    totalActivities: 42,
    createdAt: '2023-05-15'
  },
  {
    user_id: 'user002',
    nickname: '健身达人',
    location: '上海',
    totalActivities: 36,
    createdAt: '2023-06-20'
  },
  {
    user_id: 'user003',
    nickname: '瑜伽教练',
    location: '广州',
    totalActivities: 28,
    createdAt: '2023-07-10'
  },
  {
    user_id: 'user004',
    nickname: '骑行一族',
    location: '深圳',
    totalActivities: 31,
    createdAt: '2023-08-05'
  },
  {
    user_id: 'user005',
    nickname: '游泳健将',
    location: '杭州',
    totalActivities: 25,
    createdAt: '2023-09-15'
  }
];

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true;
  try {
    // 尝试添加/api前缀
    const response = await fetch('http://localhost:8080/api/users');
    const data = await response.json();
    console.log('获取到的用户列表:', data);
    
    // 确保用户数据格式统一
    users.value = data.map(user => ({
      user_id: user.userId || user.id || user.username,
      nickname: user.nickname || user.username,
      avatar_url: user.avatarUrl || user.avatar,
      location: user.location || user.city || '未知',
      totalActivities: user.totalActivities || user.postCount || 0,
      createdAt: user.createdAt || user.createTime
    }));
    
    // 默认按活动总数排序
    users.value.sort((a, b) => b.totalActivities - a.totalActivities);
    
  } catch (error) {
    console.error('获取用户列表失败，使用模拟数据:', error);
    // 使用模拟数据
    users.value = mockUsers;
  } finally {
    loading.value = false;
  }
};

// 选择用户
const selectUser = (userId) => {
  emit('select-user', userId);
};

// 重置用户选择，查看全部用户数据
const viewAllUsers = () => {
  emit('select-user', '');
  // 如果当前无数据，则重新获取
  if (users.value.length === 0) {
    fetchUsers();
  }
};

// 生成随机颜色
const getRandomColor = (userId) => {
  // 根据用户ID生成固定颜色
  const colors = [
    '#35B55F', '#4E9AEF', '#F5A623', '#FC6CA9', 
    '#6C5CE7', '#00D2D3', '#FD9644', '#2ED573'
  ];
  
  const index = userId.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0) % colors.length;
  return colors[index];
};

onMounted(() => {
  console.log('UserList组件已挂载，开始获取用户数据');
  fetchUsers();
});
</script>

<template>
  <div class="user-list-container">
    <div class="user-list-header">
      <h3>用户列表</h3>
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索用户..."
        />
      </div>
    </div>
    
    <div class="view-all-btn" @click="viewAllUsers">
      <span class="all-icon">👥</span>
      <span>查看全部用户数据</span>
    </div>
    
    <div v-if="loading" class="loading-indicator">
      加载中...
    </div>
    
    <div v-else class="user-list">
      <div 
        v-for="user in filteredUsers" 
        :key="user.user_id"
        class="user-card"
        :class="{ active: user.user_id === selectedUserId }"
        @click="selectUser(user.user_id)"
      >
        <div class="user-avatar" :style="{ backgroundColor: getRandomColor(user.user_id) }">
          {{ user.nickname ? user.nickname.charAt(0) : '?' }}
        </div>
        <div class="user-info">
          <div class="user-name">{{ user.nickname }}</div>
          <div class="user-location">{{ user.location }}</div>
          
          <div class="user-activity-summary">
            <div class="activity-count">
              <span class="count">{{ user.totalActivities || 0 }}</span>
              <span class="label">总活动</span>
            </div>
          </div>
        </div>
      </div>
      
      <div v-if="filteredUsers.length === 0" class="no-results">
        没有找到匹配的用户
      </div>
    </div>
  </div>
</template>

<style scoped>
.user-list-container {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  padding: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.user-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.user-list-header h3 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

.search-box {
  position: relative;
}

.search-box input {
  padding: 6px 12px;
  border: 1px solid #eaeaea;
  border-radius: 4px;
  font-size: 13px;
  width: 150px;
}

.view-all-btn {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f0f7ff;
  border-radius: 6px;
  margin-bottom: 15px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.view-all-btn:hover {
  background-color: #e0edff;
}

.all-icon {
  font-size: 18px;
  margin-right: 8px;
}

.user-list {
  flex: 1;
  overflow-y: auto;
}

.user-card {
  display: flex;
  align-items: center;
  padding: 12px 10px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
  margin-bottom: 8px;
}

.user-card:hover {
  background-color: #f5f7fa;
}

.user-card.active {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #35B55F;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  margin-right: 12px;
  flex-shrink: 0;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
  margin-bottom: 2px;
}

.user-location {
  color: #888;
  font-size: 12px;
  margin-bottom: 8px;
}

.user-activity-summary {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.activity-count {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.activity-count .count {
  font-weight: 600;
  color: #35B55F;
  font-size: 15px;
}

.activity-count .label {
  font-size: 12px;
  color: #999;
}

.loading-indicator, .no-results {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
  font-size: 14px;
}
</style> 